package com.home.fansea.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.home.fansea.constant.RedisConstants;
import com.home.fansea.entity.Friend;
import com.home.fansea.entity.Result;
import com.home.fansea.entity.User;
import com.home.fansea.mapper.UserMapper;
import com.home.fansea.service.FriendService;
import com.home.fansea.service.TokenService;
import com.home.fansea.service.UserService;
import com.home.fansea.utils.ShiroUtils;
import com.home.fansea.utils.UserHolder;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Projectname: MiniXYIot
 * @Filename: UserLoginController
 * @Author: FANSEA
 * @Data:2024/5/19 9:21
 */
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    LoadingCache<Long,User> userCache;

    @Resource
    private TokenService tokenService;

    @Autowired
    private UserService userService;

    @Autowired
    private FriendService friendService;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;


    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpSession httpSession){
        String username = user.getUserName();
        String password = user.getPassword();
        System.out.println("用户名："+username+"密码："+password);
        /*//1.初始化获取SecurityManager
        IniSecurityManagerFactory factory=new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager instance = factory.getInstance();
        SecurityUtils.setSecurityManager(instance);*/
        //2.获取Subject对象
        Subject subject = SecurityUtils.getSubject();
        //3.创建token对象，web应用从前端传递用户名和密码
        AuthenticationToken token=new UsernamePasswordToken(username,password);
        //4.完成登录
        try {
            subject.login(token);
            if (subject.isAuthenticated()){
                System.out.println("登录成功");
                //将用户名存储到session对象中
                httpSession.setAttribute("userName",user.getUserName());
                User userx = userService.getOne(new QueryWrapper<User>().eq("user_name", username));
//                subject.getSession().setAttribute("user",userx);
//                ShiroUtils.setUser(userx);
                UserHolder.saveUser(userx);
                String tokens = tokenService.createToken(userx);
                return Result.ok(tokens);
            }
        }catch (UnknownAccountException e){
            e.printStackTrace();
            System.out.println("用户不存在");
            return Result.fail("用户不存在！");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误");
            return Result.fail("密码错误!");
        }
        return Result.fail("登录失败");
    }

    @GetMapping("/logout")
    public Result logout(){
        tokenService.removeToken(RedisConstants.USER_LOGIN_KEY + ShiroUtils.getUser().getId());
        return Result.ok("账号注销！");
    }

    @GetMapping("/friend")
    public Result getFriends(){
        Long id = ShiroUtils.getUser().getId();
        friendService.getOne(new QueryWrapper<Friend>().eq("user_id",id));
        return null;
    }
    @GetMapping("/{id}")
    public Result getUser(@PathVariable Long id){
        User user = userCache.get(id);
        return Result.ok(user);
    }
    @GetMapping("/test")
    public Result test(){
        //Mybatis默认开启缓存
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.selectById(1);
        System.out.println("user = " + user);
        User user1 = mapper.selectById(1);
        return Result.ok(user1);
    }
}
